import React from 'react';
import _ from 'lodash';
import { history } from 'umi';
import { notification } from 'antd';
import SystemHeader from '@/components/SystemHeader';
import SystemFooter from '@/components/SystemFooter';
import SystemMenu from '@/components/SystemMenu';
import SystemLoading from '@/components/SystemLoading';
import RootContainer from '@/components/RootContainer';
import { checkToken } from '@/services/user';
import { fetchUserInformation, fetchRouteResource } from '@/services/user/base';
import { initRouteMaps, getRouteExtraOptions, getOriginalPath } from '@/utils/routeFormat';
import { getToken, getTheme } from '@/utils/auth';
import requestConfig from '@/utils/requestConfig';
import defaultSettings from '@/../config/defaultSettings';

const loginPath = '/login'; // 登录页路径

/** 系统初始化比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <SystemLoading />,
};

/** 初始权限判断，若没有token则前往登录页 */
export function render(oldRender) {
  if (!getToken()) {
    history.push(loginPath);
  }
  oldRender();
}

/** 项目初始化公共数据（用户信息、权限路由） */
export async function getInitialState() {
  // 校验token是否有效
  const checkUserToken = () => {
    return new Promise((resolve) => {
      try {
        setTimeout(() => {
          checkToken()
            .then(() => {
              resolve(true);
            })
            .catch((e) => {
              resolve();
            });
        }, 0);
      } catch (e) {
        resolve();
      }
    });
  };
  // 获取用户信息
  const getUserInfo = () => {
    return new Promise((resolve) => {
      try {
        setTimeout(() => {
          fetchUserInformation()
            .then((res) => {
              resolve(_.isPlainObject(res) ? res : {});
            })
            .catch(() => {
              resolve({});
            });
        }, 0);
      } catch (e) {
        resolve({});
      }
    });
  };
  // 获取资源列表
  const getRouterResources = () => {
    return new Promise((resolve) => {
      try {
        setTimeout(() => {
          fetchRouteResource()
            .then((res) => {
              if (_.isArray(res)) {
                const menuData = initRouteMaps(res);
                const { routePathList, defaultUrl } = getRouteExtraOptions(menuData);
                if (!menuData.length) {
                  notification.warning({
                    message: '资源获取失败',
                    description: '您当前暂无可访问的页面资源',
                  });
                }
                resolve({ menuData, routePathList, defaultUrl });
              } else {
                resolve({ menuData: [], routePathList: {}, defaultUrl: '' });
              }
            })
            .catch((e) => {
              console.log('初始化用户资源树异常', e);
              resolve({ menuData: [], routePathList: {}, defaultUrl: '' });
            });
        }, 0);
      } catch (e) {
        console.log('初始化用户资源树异常', e);
        resolve({ menuData: [], routePathList: {}, defaultUrl: '' });
      }
    });
  };

  // 主题配置属性
  let nextSettings = defaultSettings;
  try {
    nextSettings = _.assign({}, defaultSettings, getTheme());
  } catch (e) {
    console.log('获取本地主题配置失败');
  }

  // 系统初始化数据
  const currentPathName = history.location.pathname;
  if (getToken() && currentPathName !== loginPath) {
    const effectiveToken = await checkUserToken();
    if (effectiveToken) {
      const userInfo = await getUserInfo();
      const { menuData, routePathList, defaultUrl } = await getRouterResources();
      if (menuData && menuData.length) {
        if (!_.includes(_.keys(routePathList), getOriginalPath(currentPathName))) {
          history.replace(defaultUrl);
        } else {
          history.replace(getOriginalPath(currentPathName));
        }
        return {
          settings: nextSettings,
          userInfo, // 用户信息
          defaultUrl, // 默认首页url
          menuData, // 当前菜单资源
          routePathList, // 菜单路径列表
          getUserInfo,
          getRouterResources,
        };
      }
    }
    history.replace(loginPath);
  }
  return {
    settings: nextSettings,
    getUserInfo,
    getRouterResources,
  };
}

/** 框架布局 */
export function layout({ initialState }) {
  return {
    menuDataRender: () => initialState.menuData || [],
    headerRender: (props) => <SystemHeader {...props} />,
    footerRender: (props) => <SystemFooter {...props} />,
    menuRender: (props) => <SystemMenu {...props} />,
    ...initialState.settings, // 主题布局切换需更新覆盖上诉配置
  };
}

/** 包装一层根组件，初始化主题配置、路由管理数据、日期模块语言配置 */
export function rootContainer(container) {
  return React.createElement(RootContainer, null, container);
}

/** dva异常捕获 */
export const dva = {
  config: {
    onError(e) {
      console.log('dva异常', e.message);
    },
  },
};

/** 接口请求全局配置 */
export const request = {
  ...requestConfig,
};
